<?php

namespace Simanx\Spes\Providers;

use Simanx\Spes\Attribute\Route\Permission\PermissionServiceProvider;
use Simanx\Spes\Commands\PermissionCacheCommand;
use Simanx\Spes\Commands\MakeModuleCommand;
use Simanx\Spes\Commands\PermissionClearCommand;
use Simanx\Spes\Commands\PublishCommand;
use Simanx\Spes\Dto\DtoServiceProvider;
use Simanx\Spes\Middlewares\Can;
use Simanx\Spes\Module\ModuleServiceProvider;

class SpesServiceProvider extends LoaderServiceProvider
{
    protected $commands = [
        MakeModuleCommand::class,
        PermissionCacheCommand::class,
        PermissionClearCommand::class,
        PublishCommand::class
    ];

    protected array $routeMiddlewares = [
        'spes.can' => Can::class
    ];

    public function register()
    {
        if ($this->app->runningInConsole()) {
            $this->commands($this->commands);
        }

        $this->publishConfig();
        $this->mergeConfigFrom(__DIR__ . '/../../config/spes.php', 'spes');
        $this->registerAttributes();
        $this->registerModule();
        $this->registerDto();
        $this->registerEvent();
        $this->registerPermission();
    }

    public function boot()
    {
        $this->registerRouteMiddleware();
    }

    public function publishConfig()
    {
        if (!$this->app->runningInConsole()) {
            return;
        }

        $this->publishes([
            __DIR__ . '/../../config/spes.php' => config_path('spes.php')
        ]);
    }

    private function registerAttributes()
    {
        $this->app->register(LoaderServiceProvider::class);
    }

    private function registerModule()
    {
        $this->app->register(ModuleServiceProvider::class);
    }

    private function registerDto()
    {
        $this->app->register(DtoServiceProvider::class);
    }

    private function registerEvent()
    {
        $this->app->register(EventServiceProvider::class);
    }

    private function registerPermission()
    {
        $this->app->register(PermissionServiceProvider::class);
    }

    protected function registerRouteMiddleware()
    {
        // register route middleware.
        foreach ($this->routeMiddlewares as $key => $middleware) {
            app('router')->aliasMiddleware($key, $middleware);
        }
    }
}